var mongoose = require("mongoose");
var productSchema = new mongoose.Schema({
    username: String,
    name: String,
    description: String,
    catagory: String,
    price: String,
    meta: {
        createAt:{
            type: Date,
            default: Date.now()
        },
        updateAt:{
            type:Date,
            default: Date.now()
        }
    }
});

//每次保存前都要执行：录入时间戳， 暂时省略
productSchema.pre('save',function(next){
    if(this.isNew){
        this.meta.createAt = this.meta.updateAt = Date.now();
    }else{
        this.meta.updateAt = Date.now();
    }
    next();
});

//定义一个静态方法，由model调用：fetch查询全部，findById单条查询
productSchema.statics = {
    findAll: function (cb) {
        return this.find({}).exec(cb);
    },
    findById: function(id, cb){
        return this.findOne({_id: id}).exec(cb);
    }
};

//导出该模式
module.exports = productSchema;